package org.flowers.unbeaten.service.impl;

import org.flowers.unbeaten.generator.configuration.DatabaseConfiguration;
import org.flowers.unbeaten.generator.constant.GeneratorConstant;
import org.flowers.unbeaten.generator.entity.FieldEntity;
import org.flowers.unbeaten.generator.entity.TableEntity;
import org.flowers.unbeaten.generator.pagination.LayPage;
import org.flowers.unbeaten.generator.pagination.Pagination;
import org.flowers.unbeaten.generator.pagination.PaginationFactory;
import org.flowers.unbeaten.service.IGeneratorService;
import org.flowers.unbeaten.util.MysqlDataBaseUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 代码生成 实现类
 * </p>
 *
 * @author RyanWang
 * @since 2021-08-13
 */
@Service
public class GeneratorServiceImpl implements IGeneratorService {

    @Autowired
    private MysqlDataBaseUtils mysqlDataBaseUtils;

    @Autowired
    private DatabaseConfiguration dataSource;


    /**
     * 获取数据库中的表
     * @param tableName 表名
     * @param tableDescribe 表描述
     * @return 数据库中的表集合(分页)
     */
    @Override
    public LayPage getTables(String tableName, String tableDescribe) {
        // 判断是否支持当前数据库
        if (!dataSource.getUrl().contains(GeneratorConstant.DB_MYSQL)) {
            return LayPage.failure("抱歉，暂不支持该数据库");
        }
        String schemaName = mysqlDataBaseUtils.getDbName(dataSource);
        Pagination page = PaginationFactory.getPagination();
        Pagination<TableEntity> data = mysqlDataBaseUtils.getTables(page, schemaName, tableName, tableDescribe);
        return LayPage.buildPagination(data);
    }

    /**
     * 获取表所有字段
     * @param tableName 表名
     * @return 表字段集合(全部)
     */
    @Override
    public LayPage getFields(String tableName) {
        String schemaName = mysqlDataBaseUtils.getDbName(dataSource);
        List<FieldEntity> list = mysqlDataBaseUtils.getFields(schemaName, tableName);
        return LayPage.buildPagination(list);
    }
}
